#!/bin/bash
#
# vidbux.com module
# Copyright (c) 2012 Plowshare team
#
# This file is part of Plowshare.
#
# Plowshare is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Plowshare is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Plowshare.  If not, see <http://www.gnu.org/licenses/>.

MODULE_VIDBUX_REGEXP_URL="http://\(www\.\)\?vidbux\.com/"

MODULE_VIDBUX_DOWNLOAD_OPTIONS="
AUTH,a,auth,a=EMAIL:PASSWORD,User account"
MODULE_VIDBUX_DOWNLOAD_RESUME=yes
MODULE_VIDBUX_DOWNLOAD_FINAL_LINK_NEEDS_COOKIE=no

MODULE_VIDBUX_UPLOAD_OPTIONS="
AUTH,a,auth,a=EMAIL:PASSWORD,User account
FOLDER,,folder,s=FOLDER,Folder to upload files into (account only)
ASYNC,,async,,Asynchronous remote upload (only start upload, don't wait for link)
CLEAR,,clear,,Clear list of remote uploads"
MODULE_VIDBUX_UPLOAD_REMOTE_SUPPORT=yes

# Output a file URL to download from Vidbux
# $1: cookie file
# $2: vidbux url
# stdout: real file download link
#         file name
vidbux_download() {
    local -r COOKIE_FILE=$1
    local -r URL=$2
    local -r BASE_URL='http://vidbux.com'
    local -r CAPTCHA_URL='/download/captcha'
    local ACCOUNT HTML FILE_ID FILE_NAME SESSION_ID JSON STATE
    local WAIT_TIME FORM RESP CHALL CAPTCHA_DATA ID
    local FNAME JS_CODE JS_CODE2

    HTML=$(curl -A "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:18.0) Gecko/18.0 Firefox/18.0" -b "$COOKIE_FILE" "$URL") || return

    # Various (temporary) errors
  if match '404.html' "$(curl -i "$URL")" || match 'No such file' "$(curl -L "$URL")" ; then
        return $ERR_LINK_DEAD
    fi

    [ -n "$CHECK_LINK" ] && return 0

    # [premium] You have reached daily quota of downloaded information for premium accounts. At the moment, the quota is 15 GB
    # [free, anon] You have reached your daily downloads limit. Please try again later.
    if match 'You have reached.*daily.*\(quota\|limit\)' "$HTML"; then
        # We'll take it literally and wait till the next day
        # Note: Consider the time zone of their server (+4:00)
        local HOUR MIN TIME

        # Get current UTC time, prevent leading zeros
        TIME=$(date -u +'%k:%M') || return
        HOUR=${TIME%:*}
        MIN=${TIME#*:}

        log_error 'Daily limit reached.'
        echo $(( ((23 - ((HOUR + 4) % 24) ) * 60 + (61 - ${MIN#0}) ) * 60 ))
        return $ERR_LINK_TEMP_UNAVAILABLE
    fi

    # If this is a premium download, we already have the download link
    if [ "$ACCOUNT" = 'premium' ]; then
        if ! match 'Click here to download' "$HTML"; then
            log_error 'Unexpected content. Site updated?'
            return $ERR_FATAL
        fi

        # Extract + output download link
        echo "$HTML" | parse 'premium_download_link' "'\(.\+\)'" || return
        echo "$FILE_NAME"
        return 0
    fi

    # Consider errors (enforced limits) which only occur for free users
    # You have reached your hourly downloads limit. Please, try again later.
    if match 'reached your hourly downloads limit' "$HTML"; then
        log_error 'Hourly limit reached.'
        echo 3600
        return $ERR_LINK_TEMP_UNAVAILABLE

    # You can`t download not more than 1 file at a time in free mode.
    elif match 'download not more than .\+ in free mode' "$HTML"; then
        log_error 'No parallel download allowed.'
        echo 120 # wait some arbitrary time
        return $ERR_LINK_TEMP_UNAVAILABLE

    # You can download files up to 500 MB in free mode.
    # This file can be downloaded by premium only
    # Note: The regexp would also match the "parallel download" error above.
    elif match 'can.*download.*\(in free mode\|premium only\)' "$HTML"; then
        return $ERR_LINK_NEED_PERMISSIONS

    # Delay between downloads must be not less than 15 min.
    # Note: We cannot just look for the text by itself because it is
    #       always present as parts of the page's javascript code.
    elif match '^[[:space:]]\+Delay between downloads' "$HTML"; then
        WAIT_TIME=$(echo "$HTML" | parse 'Delay between downloads' \
            'not less than \([[:digit:]]\+\) min') || return

        log_error 'Forced delay between downloads.'
        echo $(( WAIT_TIME * 60 ))
        return $ERR_LINK_TEMP_UNAVAILABLE
    fi
    
    # Parse file name from page title
   # FILE_NAME=$(echo "$HTML" | parse_tag 'title') || return
   # FILE_NAME=${FILE_NAME#Download file }

    # Extract file ID from URL
    FILE_ID=$(echo "$URL" | parse . \
        'vidbux\.com\/\([[:alnum:]]\+\)') || return
    log_debug "File ID: $FILE_ID"
    
    FNAME=$(echo "$HTML" | parse_attr 'fname' 'value') || return

        log_debug 'Solve Media CAPTCHA found'

        RESP=$(solvemedia_captcha_process '4Si2SlTjio.ym0WwkVekSCNgnowF5fCX') || return
        { read CHALL; read ID; } <<< "$RESP"

        CAPTCHA_DATA="-d adcopy_challenge=$(echo "$CHALL" | uri_encode_strict) -d adcopy_response=manual_challenge"

    log_debug "Captcha data: $CAPTCHA_DATA"
    
    # Get download link (Note: No quotes around $CAPTCHA_DATA!)
    HTML=$(curl $URL --referer "$URL" $CAPTCHA_DATA -d "op=download1&method_free=1&id=$FILE_ID&fname=$FNAME" ) || return
    # HTML=$(echo "$HTML" | break_html_lines_alt )
   # echo $HTML > HTML
   # if ! match 'Click here to download' "$HTML"; then
   #     local FAIL_COOKIE
   #     FAIL_COOKIE=$(parse_cookie_quiet 'failed_on_captcha' < "$COOKIE_FILE")

   #     if match 'verification code is incorrect' "$HTML" || \
   #         [ $FAIL_COOKIE -eq 1 ]; then
   #         captcha_nack $ID
   #         return $ERR_CAPTCHA
   #     fi

   #     log_error 'Unexpected content. Site updated?'
   #     return $ERR_FATAL
   # fi

    captcha_ack $ID
    log_debug 'Correct captcha'
    
    # Obfuscated javascript
   # echo  $HTML > vidbuxhtml
   # JS_CODE=$(echo "$HTML" | parse 'split(' '>\(.*\)$') || echo "okay"
   JS_CODE=$(echo $HTML | sed 's/.*p,a,c,k//;s/<\/script.*//' )
   echo $JS_CODE > jscode
    JS_CODE2=$(echo "eval = function(x) { print(x); }; eval(function(p,a,c,k$JS_CODE" | javascript) || return
    echo $JS_CODE2 > jscode2
    
    JS_CODE2=${JS_CODE2:222}
    # JS_CODE2=${JS_CODE2%???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
   JS_CODE2=$(echo $JS_CODE2 | sed "s/'.*//g" )
   # FILE_URL=$( echo "$JS_CODE2" | replace "'" '"' | parse 'location' 'href' )
    FILE_URL=$( echo "$JS_CODE2" )
    echo "$FILE_URL"
    echo "$FNAME"
}
